﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Nxg.Blog.Core.Documents {
    public class BlogPost {
        [Key, DatabaseGenerated (DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Required, MaxLength (50)]
        public string Title { get; set; }

        [Required, MaxLength (50)]
        public string TitleSlug { get; set; }

        [NotMapped]
        public string Description {
            get {
                if (string.IsNullOrWhiteSpace (Content))
                    return string.Empty;
                var des = Regex.Replace (Content, "<[^>]+>", string.Empty).Trim ();
                var length = des.Length < 240 ? des.Length : 240;
                des = des.Substring (0, length) + " ...";
                return des;
            }
        }

        [Required]
        public int ViewCount { get; set; }

        [Required]
        public string MarkDown { get; set; }

        [Required]
        public string Content { get; set; }

        [Required]
        public PublishStatus Status { get; set; }

        [Required]
        public DateTime PubDate { get; set; }

        [Required]
        public string Tags { get; set; }

        [Required]
        public string AuthorDisplayName { get; set; }

        [Required, EmailAddress]
        public string AuthorEmail { get; set; }

        public int? CategoryId { get; set; }

        [NotMapped]
        public bool IsPublished {
            get { return PubDate <= DateTime.Now && Status == PublishStatus.Published; }
        }

        public string GetLink () {
            if (!IsPublished) {
                return "#";
            }
            return "/{0}/{1}".FormatWith (PubDate.ToString ("yyyy/MM", CultureInfo.InvariantCulture), TitleSlug);
        }
    }
    public static class BlogPostExtensions {
        public static BlogPost ToPublishedBlogPost (this BlogPost blogPost) {
            blogPost.PubDate = DateTime.Now.AddDays (-1);
            blogPost.Status = PublishStatus.Published;
            return blogPost;
        }

    }
}